package pailaidai.hc.com.mysvgdemo.base64pass;

import android.util.Base64;
import android.util.Log;


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Description:说明
 * @Author:xgchen
 * @Date:2016-07-11 15:58
 * @Version:V0.0.1
 */
public class AESEncrypt {

    private static final String ALGORITHM = "AES";
    /**
     * "算法/模式/补码方式"
     */
    private static final String AES_CBC_PKCS5_PADDING = "AES/CBC/PKCS7Padding";
    private static final String IV_PARAMETER_SPEC = Key.IV_PARAMETER_SPEC();

    /**
     * 随机生成秘钥
     */
    public static String getKey(){
        try {
            KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(128);//要生成多少位，只需要修改这里即可128, 192或256
            SecretKey sk = kg.generateKey();
            byte[] b = sk.getEncoded();
            String s = byteToHexString(b);
            Log.i("AESEncrypt",s);
            Log.i("AESEncrypt","十六进制密钥长度为"+s.length());
            Log.i("AESEncrypt","二进制密钥的长度为"+s.length()*4);
            return s;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            Log.i("AESEncrypt","没有此算法。");
        }
        return null;
    }

    /**
     * 使用指定的字符串生成秘钥
     */
    public static void getKeyByPass(){
        //生成秘钥
        String password="testkey";
        try {
            KeyGenerator kg = KeyGenerator.getInstance("AES");
            // kg.init(128);//要生成多少位，只需要修改这里即可128, 192或256
            //SecureRandom是生成安全随机数序列，password.getBytes()是种子，只要种子相同，序列就一样，所以生成的秘钥就一样。
            kg.init(128, new SecureRandom(password.getBytes()));
            SecretKey sk = kg.generateKey();
            byte[] b = sk.getEncoded();
            String s = byteToHexString(b);
            Log.i("AESEncrypt",s);
            Log.i("AESEncrypt","十六进制密钥长度为"+s.length());
            Log.i("AESEncrypt","二进制密钥的长度为"+s.length()*4);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.println("没有此算法。");
        }
    }

    /**
     * byte数组转化为16进制字符串
     * @param bytes
     * @return
     */
    public static String byteToHexString(byte[] bytes){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String strHex=Integer.toHexString(bytes[i]);
            if(strHex.length() > 3){
                sb.append(strHex.substring(6));
            } else {
                if(strHex.length() < 2){
                    sb.append("0" + strHex);
                } else {
                    sb.append(strHex);
                }
            }
        }
        return  sb.toString();
    }

    /**
     * AES cbc加密
     *
     * @param content 待加密明文
     * @param key     aes秘钥
     * @return
     * @throws Exception byte []
     */
    public static String encryptCBC(String content, String key) throws Exception {
        //反序列化AES密钥
        Security.addProvider(new BouncyCastleProvider());
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER_SPEC.getBytes());
        //初始化加密器并加密

        Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        byte[] encryptBytes = cipher.doFinal(content.getBytes("UTF-8"));
        return new String(Base64.encode(encryptBytes,Base64.DEFAULT));
    }
    /**
     * AES cbc解密
     *
     * @param content 密文
     * @param key     aes密钥
     * @return 原文
     * @throws Exception
     */
    public static String decryptCBC(String content, String key) throws Exception {
        //反序列化AES密钥
        Security.addProvider(new BouncyCastleProvider());
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER_SPEC.getBytes());
        //初始化加密器并加密
        Cipher deCipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        deCipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
        byte[] decode = Base64.decode(content.getBytes("UTF-8"), Base64.DEFAULT);
        byte[] bytes = deCipher.doFinal(decode);
        return new String(bytes);
    }



}
